﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MemcachedDemo.Library.Common;
using System.Collections;
using System.Configuration;
using System.Web;
using System.Web.Caching;
using MemcachedDemo.Library.Client;

namespace MemcachedDemo.Library.Config
{
    public class MemcachedConfigManager
    {
        static MemcachedConfigManager()
        {
            CacheDependency cacheDependency = new CacheDependency(ConfigFilePath);
            HttpRuntime.Cache.Add("_MemcachedConfigFile_", new object(), cacheDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.High
                , new CacheItemRemovedCallback(RemovedCallback));
        }

        private static void RemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            if (reason == CacheItemRemovedReason.DependencyChanged)
            {
                MemcachedManager.Reset();
            }
        }

        public static string ConfigFilePath
        {
            get
            {
                var path = ConfigurationManager.AppSettings["MemcachedConfigPath"] ?? "~/Config/Memcached.config";
                if (HttpContext.Current == null)
                    return AppDomain.CurrentDomain.BaseDirectory + @"Config\Memcached.config";
                return HttpContext.Current.Server.MapPath(path);
            }
        }

        public static MemcachedSettings Settings
        {
            get
            {
                return SerializerUtility.DeserializeFromXmlFile(ConfigFilePath, typeof(MemcachedSettings)) as MemcachedSettings;
            }
        }

        public static string[] GetServers(ServerInfoCollection serverList)
        {
            #region
            var servers = "";
            foreach (ServerInfo item in serverList)
            {
                servers += "," + string.Concat(item.Ip, ":", item.Port);
            }
            servers = servers.Trim(',');
            return servers.Split(',');
            #endregion
        }

        public static int[] GetWeights(ServerInfoCollection serverList)
        {
            #region
            int[] result = new int[serverList.Count];
            var i = 0;
            foreach (ServerInfo item in serverList)
            {
                result[i] = item.Weight;
                i++;
            }
            return result;
            #endregion
        }
    }
}
